package com.atgugu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atgugu.realtime.app.BaseAppV2;
import com.atgugu.realtime.bean.VisitorStats;
import com.atgugu.realtime.common.Constant;
import com.atgugu.realtime.util.AtguiguUtil;
import com.atgugu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.HashMap;

import static com.atgugu.realtime.common.Constant.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/31 11:25
 */
public class DwsVisitorStatsApp_1 extends BaseAppV2 {
    public static void main(String[] args) {
        new DwsVisitorStatsApp_1().init(4001, 1, "DwsVisitorStatsApp_1", "DwsVisitorStatsApp_1",
                                        TOPIC_DWD_PAGE, Constant.TOPIC_DWM_UV, Constant.TOPIC_DWM_UJ);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       HashMap<String, DataStreamSource<String>> topicToStream) {
        
        // 1. 把多个流union成一个流
        DataStream<VisitorStats> vsStream = parseAndUnionOne(topicToStream);
        
        // 2. 开窗聚合
        SingleOutputStreamOperator<VisitorStats> aggregatedStream = windowAndAggregate(vsStream);
        
        // 3. 数据写入到ClickHouse中
        writeToClickHouse(aggregatedStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<VisitorStats> stream) {
        stream.addSink(FlinkSinkUtil.getClickHouseSink("gmall2021", "visitor_stats_2021", VisitorStats.class));
    }
    
    private SingleOutputStreamOperator<VisitorStats> windowAndAggregate(DataStream<VisitorStats> vsStream) {
        return vsStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                    .withTimestampAssigner((vs, ts) -> vs.getTs())
            )
            .keyBy(vs -> vs.getVc() + "_" + vs.getCh() + "_" + vs.getAr() + "_" + vs.getIs_new())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .sideOutputLateData(new OutputTag<VisitorStats>("late") {})
            .reduce(
                new ReduceFunction<VisitorStats>() {
                    @Override
                    public VisitorStats reduce(VisitorStats vs1,
                                               VisitorStats vs2) throws Exception {
                        vs1.setUv_ct(vs1.getUv_ct() + vs2.getUv_ct());
                        vs1.setPv_ct(vs1.getPv_ct() + vs2.getPv_ct());
                        vs1.setSv_ct(vs1.getSv_ct() + vs2.getSv_ct());
                        vs1.setUj_ct(vs1.getUj_ct() + vs2.getUj_ct());
                        vs1.setDur_sum(vs1.getDur_sum() + vs2.getDur_sum());
                        return vs1;
                    }
                },
                new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<VisitorStats> elements,
                                        Collector<VisitorStats> out) throws Exception {
                        VisitorStats vs = elements.iterator().next();
                        
                        String stt = AtguiguUtil.toDataTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDataTime(ctx.window().getEnd());
                        
                        vs.setStt(stt);
                        vs.setEdt(edt);
                        
                        vs.setTs(System.currentTimeMillis());// 把ts更新为当前系统时间
                        
                        out.collect(vs);
                    }
                }
            );
        
    }
    
    private DataStream<VisitorStats> parseAndUnionOne(HashMap<String, DataStreamSource<String>> topicToStream) {
        // 1. 用于计算pv 和持续访问时间
        SingleOutputStreamOperator<VisitorStats> pvAndDurSumStream = topicToStream
            .get(TOPIC_DWD_PAGE)
            .map(line -> {
                JSONObject obj = JSON.parseObject(line);
                
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long ts = obj.getLong("ts");
                
                Long dur_sum = obj.getJSONObject("page").getLong("during_time");
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        0L, 1L, 0L, 0L, dur_sum,
                                        ts);
                
            });
        // 2. 计算uv
        SingleOutputStreamOperator<VisitorStats> uvStream = topicToStream
            .get(TOPIC_DWM_UV)
            .map(line -> {
                JSONObject obj = JSON.parseObject(line);
                
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long ts = obj.getLong("ts");
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        1L, 0L, 0L, 0L, 0L,
                                        ts);
                
            });
        
        // 3. 计算uj
        SingleOutputStreamOperator<VisitorStats> ujStream = topicToStream
            .get(TOPIC_DWM_UJ)
            .map(line -> {
                JSONObject obj = JSON.parseObject(line);
                
                JSONObject common = obj.getJSONObject("common");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long ts = obj.getLong("ts");
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        0L, 0L, 0L, 1L, 0L,
                                        ts);
                
            });
        // 4. 计算sv
        SingleOutputStreamOperator<VisitorStats> svStream = topicToStream
            .get(TOPIC_DWD_PAGE)
            .flatMap(new FlatMapFunction<String, VisitorStats>() {
                @Override
                public void flatMap(String line,
                                    Collector<VisitorStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(line);
                    
                    if (obj.getJSONObject("page").getString("last_page_id") == null) {
                        JSONObject common = obj.getJSONObject("common");
                        String vc = common.getString("vc");
                        String ch = common.getString("ch");
                        String ar = common.getString("ar");
                        String is_new = common.getString("is_new");
                        
                        Long ts = obj.getLong("ts");
                        
                        out.collect(new VisitorStats("", "",
                                                     vc, ch, ar, is_new,
                                                     0L, 0L, 1L, 0L, 0L,
                                                     ts));
                        
                    }
                }
            });
        
        return pvAndDurSumStream.union(uvStream, ujStream, svStream);
    }
}
